package ysq.xyg.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import ysq.weixin.client.WxApiClient;
import ysq.weixin.client.WxMemoryCacheClient;
import ysq.weixin.model.info.JSTicketShareResponse;
import ysq.xyg.model.*;
import ysq.xyg.model.info.*;
import ysq.xyg.service.*;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;
import ysq.xyg.util.ProProperties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yu sheng qiang
 * @create 2017-03-22 11:57
 **/
@Controller
public class PhoneController {
    private static Logger log= LoggerFactory.getLogger(PhoneController.class);
    @Resource
    private WebConfigService webConfigService;
    @Resource
    private WebNavigationService webNavigationService;
    @Resource
    private WebCooperateService webCooperateService;
    @Resource
    private WebItemService webItemService;
    @Resource
    private WebCatalogService webCatalogService;
    @Resource
    private InformationService informationService;
    @Resource
    private BannerService bannerService;
    @Resource
    private ProductService productService;
    @Resource
    private ArticleService articleService;
    @Resource
    private WebMessageService webMessageService;
    @Resource
    private MemberService memberService;
    @Resource
    private DbShareService dbShareService;
    @Resource
    private WebFileService webFileService;
    @Resource
    private WebSubService webSubService;
    private ModelAndView checkModelAndView;
    private  Member member;
    /**
     * 首页
     * */
    @RequestMapping(value="/phone/index")
    public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView("/mobile/index");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("bannerList",acceptBannerList());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        List<WebCatalog> webCatalogList=webCatalogService.list(new WebCatalog());

        if(webCatalogList!=null&&webCatalogList.size()>0){
            for(WebCatalog webCatalog:webCatalogList){
                List<Information> informationList=informationService.list(new Information(webCatalog.getId(),"1","1"));
                webCatalog.setInformationList(informationList);
            }
        }
        List<WebCooperate> list=webCooperateService.list(new WebCooperate());
        modelAndView.addObject("webCatalogList",webCatalogList);
        modelAndView.addObject("webCooperateList",list);
        return modelAndView;
    }
    /**
     * 联系我们
     * */
    @RequestMapping(value="/phone/linkMe")
    public ModelAndView linkMe(HttpServletRequest request,HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView("/mobile/linkMe");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("bannerList",acceptBannerList());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        return modelAndView;
    }
    /**
     * 联系我们
     * */
    @RequestMapping(value = "/phone/webMessage",method = RequestMethod.POST)
    public @ResponseBody
    JSONObject webMessage(HttpServletRequest request, WebMessage webMessage){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        webMessage.setId(BaseUtil.uId());
        webMessage.setType("1");
        webMessage.setCreateTime(new Date());
        int num=webMessageService.insert(webMessage);
        if(num<0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"提交失败");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }else{
            returnInfo.setResult(webMessage.getId());
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 产品
     * */
    @RequestMapping(value="/phone/product")
    public ModelAndView product(HttpServletRequest request,HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView("/mobile/productList");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("bannerList",acceptBannerList());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        modelAndView.addObject("productList",acceptProductList(new Product("1")));
        return modelAndView;
    }
    /**
     * 产品详情
     * */
    @RequestMapping(value="/phone/product/{id}")
    public ModelAndView detail(HttpServletRequest request, HttpServletResponse response,@PathVariable("id") String id){
        ModelAndView modelAndView=new ModelAndView("/mobile/productDesc");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        modelAndView.addObject("product",productService.selectByPrimaryKey(id));
        return modelAndView;
    }
    /**
     * 文章展示内容
     * */
    @RequestMapping(value="/phone/articleAll/{id}")
    public ModelAndView articleAll(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id){
        ModelAndView modelAndView=new ModelAndView("/mobile/articleAll");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        Article article=articleService.selectByPrimaryKey(id);
        modelAndView.addObject("article",articleService.selectByPrimaryKey(id));
        return modelAndView;
    }
    /**
     * 文章
     * */
    @RequestMapping(value="/phone/article/{id}")
    public ModelAndView article(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id){
        ModelAndView modelAndView=new ModelAndView("/phone/content");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("bannerList",acceptBannerList());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        modelAndView.addObject("article",articleService.selectByPrimaryKey(id));
        return modelAndView;
    }
    /**
     * 资讯
     * */
    @RequestMapping(value="/phone/news")
    public ModelAndView news(HttpServletRequest request,HttpServletResponse response,Information information){
        ModelAndView modelAndView=new ModelAndView("/mobile/news");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("bannerList",acceptBannerList());
        List<WebCatalog> webCatalogList=webCatalogService.list(new WebCatalog());
        modelAndView.addObject("webCatalogList",webCatalogList);
        List<Information> informationListYsqw=null;
        List<Information> webCatalogListQyyl=null;
        List<Information> webCatalogListCjwt=null;
        //1、医事趣闻，2、前沿医疗，3、常见问题，4、活动优惠
        if(webCatalogList!=null&&webCatalogList.size()>0){
            for (WebCatalog webCatalog:webCatalogList){
                if("1".equals(webCatalog.getType())){
                    informationListYsqw=informationService.list(new Information(webCatalog.getId(),"1","1"));
                }else if("2".equals(webCatalog.getType())){
                    webCatalogListQyyl=informationService.list(new Information(webCatalog.getId(),"1","1"));
                }else if("3".equals(webCatalog.getType())){
                    webCatalogListCjwt=informationService.list(new Information(webCatalog.getId(),"1","1"));
                }
            }
        }
        modelAndView.addObject("informationListYsqw",informationListYsqw);
        modelAndView.addObject("webCatalogListQyyl",webCatalogListQyyl);
        modelAndView.addObject("webCatalogListCjwt",webCatalogListCjwt);
        return modelAndView;
    }
    /**
     * 资讯
     * */
    @RequestMapping(value="/phone/newsCatologe/{id}")
    public ModelAndView newsCatologe(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id){
        ModelAndView modelAndView=new ModelAndView("/mobile/newsList");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        modelAndView.addObject("webCatalogList",webCatalogService.list(new WebCatalog()));
        modelAndView.addObject("bannerList",acceptBannerList());
        modelAndView.addObject("webCatalog",webCatalogService.selectByPrimaryKey(id));
        List<Information> informationList=informationService.list(new Information(id,"1",""));;
        modelAndView.addObject("informationList",informationList);
        return modelAndView;
    }
    /**
     * 资讯详情
     * */
    @RequestMapping(value="/phone/news/{id}")
    public ModelAndView news(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id){
        ModelAndView modelAndView=new ModelAndView("/mobile/newsDesc");
        modelAndView.addObject("webConfig",acceptWebConfig());
        modelAndView.addObject("navigationList",acceptWebNavigation());
        modelAndView.addObject("information",informationService.selectByPrimaryKey(id));
        return modelAndView;
    }
    /**
     * 获取web基础配置
     */
    public WebConfig acceptWebConfig(){
       List<WebConfig> list = webConfigService.selectAll();
       if(list!=null&&list.size()>0){
           return list.get(0);
       }else{
           return null;
       }
    }

    /**
     * 获取banner配置
     */
    public List<Banner> acceptBannerList(){
        return bannerService.list(new Banner(BaseConstant.BANNER_IS_PHONE,BaseConstant.STATUS_IS_YES));    }

    /**
     * 获取产品
     */
    public List<Product> acceptProductList(Product product){
        return productService.list(product);
    }


    /**
     * 注册信息
     */
    @RequestMapping("/phone/register")
    public ModelAndView register(HttpServletRequest request,String memberId) {
        if(!check(memberId, BaseConstant.WX_STATE_TWO)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/register");
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }

    /**
     * 预约服务
     */
    @RequestMapping("/phone/webSub")
    public ModelAndView webSub(HttpServletRequest request,String memberId,String page) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        WebItem webItem=new WebItem();
        //类别:1、疫苗接种，2、基因检测，3、医学美容，4、其他医疗服务
        if("childSub".equals(page)){
            webItem.setType("1");
        }else if("genSub".equals(page)){
            webItem.setType("2");
        }else if("medicSub".equals(page)){
            webItem.setType("3");
        }else if("proSub".equals(page)){
            webItem.setType("4");
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/"+page);
        List<WebItem> webItemList=webItemService.list(webItem);
        List<Map<String,String>> reslutList=new ArrayList<Map<String, String>>();
        if(webItemList!=null&&webItemList.size()>0) {
            for (WebItem webItem1 : webItemList) {
                Map<String, String> map = new HashedMap();
                map.put("title", webItem1.getName());
                map.put("value", webItem1.getMoney());
                reslutList.add(map);
            }
            modelAndView.addObject("itemSelectStr",  JSONArray.toJSONString(reslutList));
        }
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);

        modelAndView.addObject("minDate", DateUtil.convertDateToString("yyyy-MM-dd",new Date()));
        modelAndView.addObject("startDate", DateUtil.convertDateToString("yyyy-MM-dd",DateUtil.getDateOfDate(new Date(),-1)));
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 跳转预约服务
     */
    @RequestMapping("/phone/webJumpSub")
    public ModelAndView webJumpSub(HttpServletRequest request,String memberId,String id) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        WebSub webSub=webSubService.selectByPrimaryKey(id);
        String url="/mobile/childSub";
        if("2".equals(webSub.getSubType())){
            url="/mobile/genSub";
        }else if("3".equals(webSub.getSubType())){
            url="/mobile/medicSubDesc";
        }else if("4".equals(webSub.getSubType())){
            url="/mobile/proSubDesc";
        }
        ModelAndView modelAndView = new ModelAndView(url);
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("webSub", webSub);
        modelAndView.addObject("member", member);
        modelAndView.addObject("minDate", DateUtil.convertDateToString("yyyy-MM-dd",new Date()));
        modelAndView.addObject("startDate",webSub.getBuyDate());
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 预约服务
     */
    @RequestMapping("/phone/webSubDesc")
    public ModelAndView webSubDesc(HttpServletRequest request,String memberId,String id) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        WebSub webSub=webSubService.selectByPrimaryKey(id);
        String url="/mobile/childSubDesc";
        if("2".equals(webSub.getSubType())){
            url="/mobile/genSubDesc";
        }else if("3".equals(webSub.getSubType())){
            url="/mobile/medicSubDesc";
        }else if("4".equals(webSub.getSubType())){
            url="/mobile/proSubDesc";
        }
        ModelAndView modelAndView = new ModelAndView(url);
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("webSub", webSub);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 个人信息
     */
    @RequestMapping("/phone/my")
    public ModelAndView my(HttpServletRequest request,String memberId) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/my");
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 服务预约
     */
    @RequestMapping("/phone/subPage")
    public ModelAndView subPage(HttpServletRequest request,String memberId) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/subPage");
        modelAndView.addObject("bannerList", bannerService.list(new Banner(BaseConstant.BANNER_IS_PHONE,BaseConstant.STATUS_IS_YES)));
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 附件信息
     */
    @RequestMapping("/phone/fileList")
    public ModelAndView fileList(HttpServletRequest request,String memberId) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/fileList");
        List<WebFile> list=webFileService.list(new WebFile());
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("list", list);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 预约信息
     */
    @RequestMapping("/phone/subList")
    public ModelAndView subList(HttpServletRequest request,String memberId) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/subList");
        List<WebSub> list=webSubService.list(new WebSub(memberId));
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("member", member);
        modelAndView.addObject("list", list);
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 预约时间修改
     */
    @RequestMapping("/phone/acceptSub")
    public ModelAndView acceptSub(HttpServletRequest request,String memberId,String subId,String page) {
        if(!check(memberId, BaseConstant.WX_STATE_ONE)){
            return checkModelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("/mobile/"+page);
        WebSub webSub=webSubService.selectByPrimaryKey(subId);
        modelAndView.addObject("memberId", memberId);
        modelAndView.addObject("webSub", webSub);
        modelAndView.addObject("member", member);
        modelAndView.addObject("minDate", DateUtil.convertDateToString("yyyy-MM-dd",new Date()));
        modelAndView.addObject("startDate",webSub.getBuyDate());
        modelAndView.addObject("jSTicketShareResponse",Share(request));
        return modelAndView;
    }
    /**
     * 预约时间信息
     */
    @RequestMapping(value = "/phone/webSubUpdate", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject webSubUpdate(WebSub webSub) {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        WebSub webSub1=webSubService.selectByPrimaryKey(webSub.getId());
        webSub1.setCheckState("1");
        webSub1.setRemarks("");
        webSub1.setUpdateNum(webSub1.getUpdateNum()+1);
        webSub1.setBuyDate(webSub.getBuyDate());
        webSub1.setBuyTime(webSub.getBuyTime());
        webSub1.setCheckTime(null);
        int num= webSubService.updateByPrimaryKey(webSub1);
        if(num<0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"预约失败");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }else{
            returnInfo.setResult(webSub.getId());
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 预约信息
     */
    @RequestMapping(value = "/phone/webSubSave", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject webSubSave(WebSub webSub) {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();

        webSub.setCreateTime(new Date());
        webSub.setCheckState("1");
        int num=0;
        if(StrUtil.isEmpty(webSub.getId())){
            webSub.setId(BaseUtil.uId());
            num= webSubService.insert(webSub);
        }else{
            webSub.setRemarks("");
            webSub.setCheckTime(null);
            num= webSubService.updateByPrimaryKey(webSub);
        }
        if(num<0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"预约失败");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }else{
            returnInfo.setResult(webSub.getId());
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 绑定用户信息
     */
    @RequestMapping(value = "/phone/bindUserSave", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject bindUserSave(MemberInfo memberInfo) {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        Member webMember=memberService.selectByPrimaryKey(memberInfo.getId());
        webMember.setName(memberInfo.getName());
        webMember.setPhone(memberInfo.getPhone());
        webMember.setType(memberInfo.getType());
        webMember.setBank(memberInfo.getBank());
        webMember.setEnglishName(memberInfo.getEnglishName());
        webMember.setCompanyName(memberInfo.getCompanyName());
        webMember.setSex(memberInfo.getSex());
        webMember.setWechat(memberInfo.getWechat());
        webMember.setAccountName(memberInfo.getAccountName());
        webMember.setAccountNum(memberInfo.getAccountNum());
        int num= memberService.updateByPrimaryKey(webMember);
        if(num<0){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,"绑定失败");
            jsonObject.put("returnInfo",returnInfo);
            return jsonObject;
        }else{
            returnInfo.setResult(webMember.getId());
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
    /**
     * 通用验证
     * */
    protected boolean check(String id, String state){
        if (StringUtil.isNotEmpty(id)) {
            member = memberService.selectByPrimaryKey(id);
            if (member != null) {
                //设置会员昵称
                if (StringUtil.isNotEmpty(member.getNickName())) {
                    member.setNickName(BaseUtil.decodeBase64(member.getNickName()));
                }
                if(state==BaseConstant.WX_STATE_ONE) {
                    if (StrUtil.isEmpty(member.getName()) || StrUtil.isEmpty(member.getPhone())) {
                        checkModelAndView = new ModelAndView("redirect:/phone/register?memberId=" + id + "&type=2");
                        return false;
                    }
                }
                return true;
            }
        }
        checkModelAndView = new ModelAndView("redirect:"+ ProProperties.getInstance().getWxOauthURL(state));
        return false;
    }
    /**
     * 通用分享可设置
     * */
    protected JSTicketShareResponse Share(HttpServletRequest request){
        WxAccountInfo wxAccountInfo= WxMemoryCacheClient.getSingleWxAccountInfo();
        String url= wxAccountInfo.getBaseURL()+request.getServletPath();
        String c=request.getQueryString();
        if(StringUtil.isNotEmpty(c)){
            url=url+"?"+c;
        }
        //设置js分享
        JSTicketShareResponse jsTicketShareResponse = WxApiClient.getJSTicketShareResponse(url);
        DbShare dbShare=dbShareService.selectDbShare();
        if(dbShare!=null&&jsTicketShareResponse!=null){
            jsTicketShareResponse.setFxTitle(dbShare.getShareTitle());
            jsTicketShareResponse.setFxImgUrl(wxAccountInfo.getBaseURL()+ dbShare.getSharePic());
            jsTicketShareResponse.setFxDesc(dbShare.getShareDesc());
            jsTicketShareResponse.setFxUrl(wxAccountInfo.getBaseURL()+ ProProperties.getInstance().getWxOauthURL(BaseConstant.WX_STATE_ONE));
            jsTicketShareResponse.setAppid(wxAccountInfo.getAppid());
        }
        return jsTicketShareResponse;
    }
    /**
     * 获取web导航配置
     */
    public List<WebNavigation> acceptWebNavigation(){
        List<WebNavigation> webNavigationList = webNavigationService.list(new WebNavigation("","2"));
        List<WebNavigation> resultList =new ArrayList<WebNavigation>();
        if(webNavigationList!=null && webNavigationList.size() > 0){
            for(WebNavigation webNavigation:webNavigationList){
                if(BaseConstant.MENU_ONE.equals(webNavigation.getGrade())){
                    if("1".equals(webNavigation.getType())){
                        //目录
                        List<WebNavigation> resultLists =new ArrayList<WebNavigation>();
                        for(WebNavigation webNavigation1:webNavigationList){
                            if(webNavigation.getId().equals(webNavigation1.getParentId())){
                                resultLists.add(webNavigation1);
                            }
                        }
                        webNavigation.setWebNavigationList(resultLists);
                    }
                    resultList.add(webNavigation);
                }
            }
        }
        return resultList;
    }
}
